package com.mapull.simple;

import java.util.Arrays;

/**
 * 冒泡排序
 * @author mapull
 * @date 2022-06-04
 */
public class Bubble {

    public static void main(String[] args) {
        int[] nums = {5,9,7,4,6,1,3,2,8};
//        int[] nums = {1,3,4,6,7,2,8,9};
//        int[] nums = {1,3,2,4,5,6,8,9};
        System.out.println("排序前 " + Arrays.toString(nums));
        bubbleSort(nums);
//        bubbleSortV2(nums);
        System.out.println("排序后 " + Arrays.toString(nums));
    }

    /**
     * 改进的冒泡排序
     */
    public static void bubbleSortV2(int[] nums){
        int cnt = nums.length - 1;
        while(true) {
            int last = 0;
            for (int j = 0; j < cnt; j++) {
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                    last = j;
                }
            }
            cnt = last;
            if(last == 0){
                break;
            }
        }
    }

    /**
     * 经典的冒泡排序
     */
    public static void bubbleSort(int[] nums){
        for(int i = 0; i< nums.length - 1; i++) {
            boolean sorted = true;
            for (int j = 0; j < nums.length - 1 - i; j++) {
                System.out.print("比较 " + nums[j] + " 与 " + nums[j+1] + "; ");
                if (nums[j] > nums[j + 1]) {
                    swap(nums, j, j + 1);
                    sorted = false;
                }
            }
            System.out.println();
            if(sorted){
                break;
            }
        }
    }

    /**
     * 数组中两数交换
     */
    public static void swap(int[] nums, int m, int n){
        int tmp = nums[m];
        nums[m] = nums[n];
        nums[n] = tmp;
    }
}
